package com.nondo.rdp.auth.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.auth.domain.Message;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.repository.MessageRepository;
import com.nondo.rdp.auth.service.MessageService;

@Transactional
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageRepository messageRepository;

    @Override
    public Message findOne(Long id) {
        return this.messageRepository.findOne(id);
    }

    @Override
    public Message save(Message message) {
        return this.messageRepository.save(message);
    }

    @Override
    public void update(Message message) {
        this.messageRepository.update(message.getTitle(), message.getContent(), message.getId());
    }
    
    @Override
    public void delete(Long id) {
        this.messageRepository.deleteById(id);
    }

    @Override
    public Page<Message> findAll(Page<Message> page, Message message) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Message> dictPage = messageRepository.findAll((root, query, builder) -> {
        	List<Predicate> predicates = new ArrayList<>();
        	if (message != null) {
        		if(message.getType() != null){
					predicates.add(builder.equal(root.get("type"), message.getType()));
				}
	            if (StringUtils.isNotEmpty(message.getTitle())) {
	                predicates.add(builder.like(root.get("title"), "%" + message.getTitle() + "%"));
	            }
        	}
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
        	
            return builder.and(predicatesArray);
        	
        }, pageRequest);

        return new Page<Message>(dictPage);
    }
}